package cn.com.huzo.service.master.impl;

import cn.com.huzo.common.util.ApplicationConfiguration;
import cn.com.huzo.model.entities.master.MaterialEntity;
import cn.com.huzo.repository.master.MaterialPictureRepository;
import huzofw.model.entities.paginator.Paginator;
import cn.com.huzo.repository.master.MaterialRepository;
import huzofw.service.impl.GenericManagerImpl;
import cn.com.huzo.service.master.MaterialManager;
import com.opencsv.CSVReader;
import huzofw.common.util.file.DeleteDirectoryAndFile;
import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.repository.master.MaterialGroupMemberMaterialRepository;

/**
 * 材料信息管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("MaterialManager")
public class MaterialManagerImpl extends GenericManagerImpl<MaterialEntity, Long>
        implements MaterialManager {

    private final String rootNodeText = (String) ApplicationConfiguration.getProperty("Catalogue_Material");
    private final String uploadPath = (String) ApplicationConfiguration.getProperty("UploadPath_Material");

    @Resource(name = "MaterialRepository")
    private MaterialRepository _dao;

    @Resource(name = "MaterialPictureRepository")
    private MaterialPictureRepository _dao_picture;

    @Resource(name = "MaterialGroupMemberMaterialRepository")
    private MaterialGroupMemberMaterialRepository _dao_material_in_group;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchByHeaderKey(Long materialId, Long currentUser, Long workFlowId) throws Exception {
        Map<String, Object> _result = new HashMap();
        _result.put("MaterialEntity", _dao.fetchByKey(rootNodeText, materialId, currentUser, workFlowId));
        _result.put("MaterialPictureList", _dao_picture.fetchAll(materialId));
        _result.put("MaterialGroupList", _dao_material_in_group.fetchByMaterialKey(materialId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> rtnValue = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<MaterialEntity> itemList = _dao.fetchForPage(criterion);
            Paginator<MaterialEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            rtnValue.put("TotalRecordCount", paginator.getTotal());
            rtnValue.put("TotalPages", paginator.getTotalPages());
            rtnValue.put("PageIndex", paginator.getPageIndex());
            rtnValue.put("DataList", paginator.getItemList());
            rtnValue.put("Success", true);
        } else {
            rtnValue.put("Success", false);
        }

        return rtnValue;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Long insert(MaterialEntity instance) throws Exception {
        Long key = _dao.insert(instance);
        // 审计日志
        if (key > 0) {
            writeAuditLog(instance.getUpdatedBy(), "基础信息→材料信息", "料号：" + instance.getMaterialCode(), "增加");
        }

        return key;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer update(MaterialEntity instance) throws Exception {
        Integer rowsAffected = _dao.update(instance);
        // 审计日志
        if (rowsAffected > 0) {
            writeAuditLog(instance.getUpdatedBy(), "基础信息→材料信息", "料号：" + instance.getMaterialCode(), "更新");
        }

        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        // 删除
        Integer rowsAffected = _dao.delete(MapUtils.getLong(criterion, "MaterialId"));
        // 删除上传的图片及目录
        if (rowsAffected > 0) {
            String dir = uploadPath + MapUtils.getLong(criterion, "MaterialId");
            DeleteDirectoryAndFile.deleteDirectory(dir);

            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "基础信息→材料信息", "料号：" + MapUtils.getString(criterion, "DeletedMaterialCode"),
                    "删除");
        }
        return fetchForPage(criterion);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer batchChangeCatalogue(List<MaterialEntity> itemList) throws Exception {
        return _dao.batchChangeCatalogue(itemList);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> importDataFromCsv(String fileName, Long userId, Long catalogueId, String materialFlag) throws Exception {
        Map<String, Object> rtnValue = new HashMap();
        int rows = 1; // 当前行数

        try (CSVReader reader = new CSVReader(new FileReader(fileName))) {
            String[] nextLine;
            //List<MaterialEntity> _dataList = new ArrayList();
            while ((nextLine = reader.readNext()) != null) {
                MaterialEntity item = new MaterialEntity();
                item.setMaterialCode(nextLine[0]);        // 品号
                item.setMaterialName(nextLine[1]);        // 品种
                item.setUnitPrice(nextLine[2].isEmpty() ? null : Float.valueOf(nextLine[2])); // 单价
                item.setUomName(nextLine[3]);             // 计量单位
                item.setMaterialComposition(nextLine[4]); // 成分
                item.setSupplierName(nextLine[5]);        // 供应商名
                item.setSpecification(nextLine[6]);       // 规格
                item.setGramWeight(nextLine[7]);          // 克重
                //item.setDyeingMinimumLot(nextLine[8].isEmpty() ? null : Float.valueOf(nextLine[8])); // 起染量
                //item.setDyingSubCharge(nextLine[9].isEmpty() ? null : Float.valueOf(nextLine[9]));   // 不足起染的染色费（小缸费）
                item.setSparedQuantity(0.03f);            // 材料损耗 默认=0.03
                item.setCatalogueId(catalogueId);         // 所属材料目录ID
                item.setMaterialFlag(materialFlag);       // 材料区分标记 
                item.setCreatedBy((long) userId);
                item.setUpdatedBy((long) userId);
                //_dataList.add(item);

                // 导入数据操作
                //_dao.importDataFromCsv(_dataList);
                _dao.importDataFromCsv(item);

                rows = rows + 1;
                //for (String subLine : nextLine) {
                //    System.out.print(subLine + " ");
                //}
            }

            rtnValue.put("Success", true);
        } catch (Exception e) {
            rtnValue.put("Success", false);
            rtnValue.put("Message", "第" + rows + "行数据有问题。");
        }

        return rtnValue;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<MaterialEntity> fetchAllFields() throws Exception {
        return _dao.fetchAllFields();
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<String> fetchExportData(Map<String, Object> criterion) throws Exception {
        List<String> itemlist = _dao.fetchExportData(criterion);

        return itemlist;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doCheck(Long materialId, Long workFlowId, Short nodeOrder, Long checkedBy, Short isCheckCurrentNode) throws Exception {
        _dao.doCheck(materialId, workFlowId, nodeOrder, checkedBy, isCheckCurrentNode);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(rootNodeText, materialId, checkedBy, workFlowId));
        _result.put("MaterialPictureList", _dao_picture.fetchAll(materialId));
        _result.put("MaterialGroupList", _dao_material_in_group.fetchByMaterialKey(materialId));
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doUnCheck(Long materialId, Long workFlowId, Short nodeOrder, Long checkedBy) throws Exception {
        _dao.doUnCheck(materialId, nodeOrder, checkedBy);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(rootNodeText, materialId, checkedBy, workFlowId));
        _result.put("MaterialPictureList", _dao_picture.fetchAll(materialId));
        _result.put("MaterialGroupList", _dao_material_in_group.fetchByMaterialKey(materialId));
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<String> fetchMaterialCodeForAutoComplate(String keyWord) throws Exception {
        return _dao.fetchMaterialCodeForAutoComplate(keyWord);
    }
}
